import { Form, message } from 'ant-design-vue'
import { type Ref, nextTick, ref } from 'vue'

import { accountApi } from '@/apis'
import type { FormState } from '@/apis/accountTypes'

type Params = {
  refresh: PromiseFunc
  checkedKeys: Ref<number[]>
  halfCheckedKeys: Ref<number[]>
  formRules: Ref<FormRules>
}

const { useForm } = Form

export function useAdd({
  refresh,
  checkedKeys,
  halfCheckedKeys,
  formRules
}: Params) {
  const formState = ref({
    id: 0,
    realName: '',
    userName: '',
    permissions: []
  } as FormState)
  const showAdd = ref(false)

  const formRef = useForm(formState, formRules)

  /** 显示 */
  async function handleShowAdd() {
    showAdd.value = true
  }

  /** 提交 */
  function handleAddAccount() {
    const newCheckedKeys = new Array<number>()
      .concat(checkedKeys.value, halfCheckedKeys.value)
      .map(item => {
        return {
          id: Number(item)
        }
      })
    formState.value.permissions = newCheckedKeys

    nextTick(() => {
      formRef
        .validate()
        .then(async () => {
          await refresh(async () => {
            try {
              await accountApi.addAccount(formState.value)
              message.success('新增成功')
              showAdd.value = false
              checkedKeys.value = []
              formRef.resetFields()
            } finally {
            }
          })
        })
        .catch((error: any) => {
          console.log('error', error)
        })
    })
  }

  /** 取消 */
  function handleAddCancel() {
    formRef.resetFields()
    checkedKeys.value = []
  }

  return {
    addFormRef: formRef,
    addFormState: formState,
    showAdd,
    handleShowAdd,
    handleAddAccount,
    handleAddCancel
  }
}
